import { logout } from "@/common/auth/token";
import { Decrypt } from "@/common/encryptHelper";
import { stopSignalRConnection } from "@/common/signalR";
import { LoadSuspense } from "@/components/loading";
import { getButtonPower } from "@/components/PowerButton";
import { flatObjArr } from "@/hy_dev_lib/src";
import { dispatchPubsub, subscribePubsub, unSubscribePubsub } from "@/hy_dev_lib/src/store";
import { routerInfo } from "@/routes";
import { useGlobalContent } from "@/store";
import { Layout, Space } from "antd";
import { useForm } from "antd/es/form/Form";
import Cookies from "js-cookie";
import React, { useEffect, useState } from "react";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import { randomUUID } from "../../common/utils";
import ErrorPage from "../404/Error";
import TopHeader from "../Home/TopHeader";
import { useGetMenu } from "../Login/useGetMenu";
import NoPermission from "../NoPermission";
import EditUserInfo from "./EditUserInfo";
import "./index.less";
import SideMenu from "./Sidemenu/SideMenu";
import SystemConfigPassword from "./SystemConfigPassword";

const { Content } = Layout;

// 页面内部适配
const notLimitSizePage = ["/home/homePage"];

const Home: React.FC<any> = (props) => {
  const { globalDispatch, global } = useGlobalContent();
  const { menuList: listData = [], initMenuData } = props;
  const flatListData = flatObjArr(listData);
  const location = useLocation();
  const [show404Content, setShow404Content] = useState(false);
  const [enterPwdOpen, setEnterPwdOpen] = useState<0 | 1>(0);
  const [routerKey, setRouterKey] = useState(randomUUID());
  // 是否需要统一限制页面最小宽度和高度
  const [pageSizeLimit, setPageSizeLimit] = useState(false);
  const { userInfoData, signalRConnection } = global || {};

  const cockpitPower = getButtonPower("e-APj_mw", global);
  const defaultShowCockpit = localStorage.getItem("defaultShowCockpit") === "1";

  const [showCockpit, setShowCockpit] = useState(cockpitPower && defaultShowCockpit); //是否展示驾驶舱
  const [userForm] = useForm();
  const [editUserInfoOpen, setEditUserInfoOpen] = useState(false);

  const { initUserInfo } = useGetMenu(globalDispatch);

  useEffect(() => {
    initUserInfo();
  }, []);

  // 退出登录时断开 singalR
  useEffect(() => {
    const sId = subscribePubsub("STOP_SIGNAL_R_CONNECTION", () => {
      stopSignalRConnection(signalRConnection);
    });
    return () => {
      unSubscribePubsub(sId);
    };
  }, [signalRConnection]);

  // console.log(cockpitPower, defaultShowCockpit, showCockpit);

  useEffect(() => {
    setShowCockpit(cockpitPower && defaultShowCockpit);
  }, [cockpitPower]);

  // 切换到驾驶舱页面
  const toCockpit = (show: any) => {
    if (show) {
      localStorage.setItem("defaultShowCockpit", "1");
    } else {
      localStorage.setItem("defaultShowCockpit", "0");
    }
    setShowCockpit(show);
  };

  //点击个人中心
  const editorUserInfo = () => {
    userForm.setFieldsValue({
      mc: userInfoData.mc || "",
      dh: userInfoData.dh || "",
      mmOld: Decrypt(userInfoData.mm),
    });
    setEditUserInfoOpen(true);
  };

  //点击用户手册
  const openUserManual = () => {
    const i = window.location.href.indexOf("?");
    let url;
    if (i > 0) {
      url = window.location.href + "&openUserManual=1";
    } else {
      url = window.location.href + "?openUserManual=1";
    }
    window.open(url, "__blank");
  };

  //点击退出系统
  const signOut = () => {
    dispatchPubsub("SHOW_TIPS_MODAL", {
      content: `您将要退出本次登录，确定吗？`,
      type: "error",
      okText: "确定",
      callback: async () => {
        logout();
        setTimeout(() => {
          localStorage.setItem("defaultShowCockpit", "");
          globalDispatch({
            type: "reset",
            data: "",
          });
        }, 500);
      },
    });
  };

  //头部右上角的个人中心
  const personItems = [
    {
      key: "1",
      label: (
        <Space className="h100" onClick={editorUserInfo}>
          个人中心
        </Space>
      ),
    },
    {
      key: "2",
      label: (
        <Space className="h100" onClick={openUserManual}>
          用户手册
        </Space>
      ),
    },
    {
      key: "3",
      label: (
        <Space size={10} className="h100" onClick={signOut}>
          退出登录
        </Space>
      ),
    },
  ];

  useEffect(() => {
    // 没有系统配置菜单项时
    if (!Cookies.get("showSystemConfigMenu")) {
      window.addEventListener("keydown", onKeyDown);
      return () => {
        window.removeEventListener("keydown", onKeyDown);
      };
    }
  }, [listData]);

  const onKeyDown = (e: any) => {
    const keyCode2 = 83; //s
    const { keyCode, shiftKey, ctrlKey, altKey } = e;
    // 按下shift+ctrl+s
    if (shiftKey && ctrlKey && keyCode === keyCode2) {
      // console.log("按下shift+ctrl+s");
      setEnterPwdOpen(1);
    }
  };

  useEffect(() => {
    if (notLimitSizePage.includes(location.pathname)) return setPageSizeLimit(false);
    setPageSizeLimit(true);
  }, [location.pathname, listData]);

  // 是否添加该项路由
  const addRouter = (menuList: any[], path: string) => {
    let t = false;
    const v = (list: any[]) => {
      list?.map((menuItem: any) => {
        if (menuItem.children?.length) {
          v(menuItem.children);
        } else if (menuItem.cdlj === path) t = true;
      });
    };
    v(menuList);
    return t;
  };

  // 用户手册页面
  if (window.location.href.includes("openUserManual"))
    return <iframe className="size100" src={"/userManual.html"}></iframe>;

  return (
    <>
      <Layout
        className="home-site-layout"
        // className={`home-site-layout mainPage ${showCockpit ? "" : "mainPageShow"}`}
        style={{ height: "100%", width: "100%" }}
      >
        <TopHeader
          showCockpit={showCockpit}
          toCockpit={toCockpit}
          personItems={personItems}
          cockpitPower={cockpitPower}
        />
        <Layout hasSider className="home modal-draggable-box">
          <SideMenu
            menuData={listData || []}
            changeMenuKey={() => {
              setRouterKey(randomUUID());
            }}
          />
          {/* 添加 home-page-container 作为弹窗 container  */}
          <Content className="home-page-container">
            <div className="all_content">
              <div className={`page-container ${pageSizeLimit ? "size-limit" : ""}`}>
                <LoadSuspense>
                  {listData && (
                    <Routes key={routerKey + listData.length}>
                      {/* {routerInfo.map(({ path, element: Ele }) => {
              return <Route key={path} path={path} element={<Ele />}></Route>;
            })} */}

                      {/* 动态渲染路由 */}
                      {routerInfo.map((router: any) => {
                        const { path, element: Ele, ...rest } = router;
                        const hasRouter = addRouter(listData, path);
                        if (hasRouter) {
                          // return (
                          //   <Route
                          //     key={path}
                          //     path={path}
                          //     element={<PowerWrap PageElement={Ele} />}
                          //   ></Route>
                          // );
                          const routePageProps = {
                            cdid: flatListData.find((v) => v.cdlj === path)?.tid || "",
                          };
                          return <Route key={path} path={path} element={<Ele {...routePageProps} />}></Route>;
                        } else {
                          return null;
                        }
                      })}

                      <Route path="404" element={<ErrorPage />}></Route>
                      <Route path="noPermission" element={<NoPermission noMenu />}></Route>
                      <Route path="*" element={<Navigate replace to="/home/404" />} />

                      {/* 当在地址栏输入的路径没有时，转到404页面 */}
                      {show404Content ? (
                        <>
                          <Route path="/404" element={<ErrorPage />}></Route>
                          <Route path="*" element={<Navigate replace to="/404" />} />
                        </>
                      ) : null}
                    </Routes>
                  )}
                  <SystemConfigPassword
                    open={enterPwdOpen}
                    setOpen={setEnterPwdOpen}
                    cb={initMenuData}
                  ></SystemConfigPassword>
                </LoadSuspense>
              </div>
            </div>
          </Content>
        </Layout>
      </Layout>
      <EditUserInfo open={editUserInfoOpen} setOpen={setEditUserInfoOpen} cb={logout} form={userForm}></EditUserInfo>
    </>
  );
};

export default Home;
